package com.example.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.enums.RoleEnum;
import com.example.entity.*;
import com.example.exception.CustomException;
import com.example.mapper.BusinessMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

@Service
public class BusinessService {
    @Resource
    private BusinessMapper businessMapper;
    @Resource
    private CollectService collectService;

    @Resource
    private CommentService commentService;
    @Resource
    private OrdersService ordersService;

    @Resource
    private OrdersItemService ordersItemService;


    public List<Business> selectAll(Business business){
        List<Business> businesses = businessMapper.selectAll(business);
        for(Business b:businesses){
            wrapBusiness(b);
        }
        return businesses;
    }
    private void wrapBusiness(Business b){
        List<Comment> comments = commentService.selectBusinessId(b.getId());
        Double sum = comments.stream().map(Comment::getStar).reduce(Double::sum).orElse(0D)+5D;
        //5+4.5/1+1
        double score = BigDecimal.valueOf(sum).divide(BigDecimal.valueOf(comments.size() + 1), 1, BigDecimal.ROUND_UP).doubleValue();
        b.setScore(score);

        //查出有效订单
        List<Orders> ordersList = ordersService.selectUsageByBusinessId(b.getId());
        int nums=0;
        for(Orders o:ordersList){
            List<OrdersItem> ordersItemList = ordersItemService.selectByOrderId(o.getId());
            nums+=ordersItemList.stream().map(OrdersItem::getNum).reduce(Integer::sum).orElse(0);
        }
        b.setNums(nums);
    }

    public void add(Business business) {
        Business dbBusiness=this.selectByUsername(business.getUsername());
        if(ObjectUtil.isNotEmpty(dbBusiness)){
            throw new CustomException(ResultCodeEnum.USER_EXIST_ERROR);
        }
        business.setRole(RoleEnum.BUSINESS.name());
        businessMapper.insert(business);
    }

    /**
     * 根据账号查询
     * @param username
     * @return
     */
    public Business selectByUsername(String username){
        Business params=new Business();
        params.setUsername(username);
        List<Business>list=this.selectAll(params);
        return list.size() == 0 ? null:list.get(0);
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    public Business selectById(Integer id){
        Business business = this.selectBasicBusinessById(id);
        if(business!=null){
            Account currentUser = TokenUtils.getCurrentUser();
            Collect collect = collectService.selectByUserIdAndBusinessId(currentUser.getId(), id);
            business.setIsCollect(collect!=null);
        }
        return business;
    }

    /**
     *
     * 查询基础商家信息
     * @param id
     * @return
     */
    public Business selectBasicBusinessById(Integer id){
        Business params=new Business();
        params.setId(id);
        List<Business>list=this.selectAll(params);
        return list.size() == 0 ? null : list.get(0);
    }

    public void updateById(Business business) {
        Business dbBusiness1=this.selectById(business.getId());
        if(ObjectUtil.isEmpty(dbBusiness1)){
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        Business dbBusiness2=this.selectByUsername(business.getUsername());
        if(ObjectUtil.isNotEmpty(dbBusiness2)&&!ObjectUtil.equals(business.getId(),dbBusiness2.getId())){
            throw new CustomException(ResultCodeEnum.USER_EXIST_ERROR);
        }
        businessMapper.updateById(business);
    }

    public void deleteById(Integer id) {
        businessMapper.deleteById(id);
    }

    public void deleteBatch(List<Integer> ids) {
        for(Integer id:ids){
            this.deleteById(id);
        }
    }
    /**
     * 分页查询
     */
    public PageInfo<Business> selectPage(Business business, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Business> list = businessMapper.selectAll(business);
        return PageInfo.of(list);
    }

    public void register(Account account) {
        Business business = new Business();
        BeanUtils.copyProperties(account,business);
        if(ObjectUtil.isEmpty(business.getName())){
            business.setName(business.getUsername());
        }
        this.add(business);
    }

    public Account login(Account account) {
        Account dbBusiness = this.selectByUsername(account.getUsername());
        if (ObjectUtil.isNull(dbBusiness)) {
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        if (!account.getPassword().equals(dbBusiness.getPassword())) {
            throw new CustomException(ResultCodeEnum.USER_ACCOUNT_ERROR);
        }
        // 生成token
        String tokenData = dbBusiness.getId() + "-" + RoleEnum.BUSINESS.name();
        String token = TokenUtils.createToken(tokenData, dbBusiness.getPassword());
        dbBusiness.setToken(token);
        return dbBusiness;
    }

    public void updatePassword(Account account) {
        Business dbBusiness = businessMapper.selectByUsername(account.getUsername());
        if (ObjectUtil.isNull(dbBusiness)) {
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        if (!account.getPassword().equals(dbBusiness.getPassword())) {
            throw new CustomException(ResultCodeEnum.PARAM_PASSWORD_ERROR);
        }
        dbBusiness.setPassword(account.getNewPassword());
        businessMapper.updateById(dbBusiness);
    }
    /**
     * 检查商家权限
     */
    public void checkBusinessAuth(){
        Account currentUser = TokenUtils.getCurrentUser();
        if(RoleEnum.BUSINESS.name().equals(currentUser.getRole())){
            Business business=selectById(currentUser.getId());
            if(!"通过".equals(business.getStatus())){
                throw new CustomException(ResultCodeEnum.NO_AUTH);
            }
        }
    }
}
